<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
      <!-- 步骤拦 -->
      <el-steps :active="dllActive*1" align-center :space="200" class>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左tab栏切换 -->
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="ruleForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="tabPosition"
          v-model="dllActive"
          :before-leave="beforeLeave"
          @tab-click="Tabschange"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="catelist"
                :props="cateprops"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单 -->
            <el-form-item :label="item.attr_name" v-for="item in tableList" :key="item.attr_id">
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item1" v-for="(item1,i1) in item.attr_vals" :key="i1" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in staticList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片 -->
    <el-dialog title="图片预览" :visible.sync="PicsVisible" width="50%">
      <span>
        <img :src="previewPath" class="picSee" />
      </span>
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash";
export default {
  data() {
    return {
      dllActive: "0",
      tabPosition: "left",
      //   添加数据表单
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        pics: [],
        // 商品的介绍
        goods_introduce: "",
        attrs: []
      },
      // 动态参数数据
      tableList: [],
      // 静态属性列表数据
      staticList: [],
      //
      addrules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      // 商品分类数据
      catelist: [],
      cateprops: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      //   商品参数列表
      tableList: [],
      // 商品属性列表
      staticList: [],
      // 上传图片地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 给图片设置请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 预览地址
      previewPath: "",
      // 图片预览对话框
      PicsVisible: false
    };
  },
  created() {
    this.getgoodslist();
  },
  methods: {
    async getgoodslist() {
      const { data: res } = await this.$http.get("categories");
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品数据失败");
      }
      this.$message.success("获取商品数据成功");
      this.catelist = res.data;
    },
    handleChange() {
      // console.log("ok");
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        return;
      }
      //   console.log(this.addForm.goods_cat[2]);
    },
    beforeLeave(activename, oldactivename) {
      // console.log("即将离开的页面"+oldactivename);
      // console.log('即将进入的页面'+activename);
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.error("请完成商品分类");
        return false;
      }
    },
    async Tabschange() {
      console.log(this.dllActive);
      if (this.dllActive == 1) {
        // console.log('商品参数');
        const { data: res } = await this.$http.get(
          `categories/${this.cartId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        // console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("获取参数列表失败");
        }
        this.$message.success("获取参数列表成功");
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals == 0 ? [] : item.attr_vals.split(" ");
        });
        this.tableList = res.data;
        // console.log(this.tableList);
      } else if (this.dllActive == 2) {
        const { data: res } = await this.$http.get(
          `categories/${this.cartId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("获取商品属性失败");
        }
        this.$message.success("获取商品属性成功");
        this.staticList = res.data;
        // console.log(this.staticList);
      }
    },
    // 图片预览
    handlePreview(file) {
      console.log(file);
      this.previewPath = file.response.data.url;
      this.PicsVisible = true;
    },
    // 图片移除
    handleRemove(file) {
      // console.log(file);
      // 获取删除图片的临时路径
      const filePath = file.response.data.tmp_path;
      // 从pics数组中找到对应的索引值
      this.addForm.pics.forEach((item, i) => {
        if (item.pic == filePath) {
          // console.log(i);
          // 调用splice方法移除图片
          this.addForm.pics.splice(i, 1);
          // console.log(this.addForm);
        }
      });
    },
    // 图片上传成功
    handleSuccess(response) {
      // console.log(response);
      if (response.meta.status !== 200) {
        return this.$message.error("图片上传失败");
      }
      this.$message.success("图片上传成功");
      const picInfo = {
        pic: response.data.tmp_path
      };
      this.addForm.pics.push(picInfo);
      // console.log(this.addForm);
    },
    add() {
      // console.log(this.addForm);
      this.$refs.ruleForm.validate(async valid => {
        console.log(valid);
        if (!valid) {
          return this.$message.error("请输入必要的表单项");
        }
        // 执行添加的业务逻辑
        const forms = _.cloneDeep(this.addForm);
        forms.goods_cat = forms.goods_cat.join(",");
        // 处理动态参数
        this.tableList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          };
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态属性
        this.staticList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          };
          this.addForm.attrs.push(newInfo);
        });
        forms.attrs=this.addForm.attrs
        console.log(forms);
       const {data:res}=await this.$http.post('goods',forms)
       console.log(res);
       if(res.meta.status!==201){
        return this.$message.error('创建商品失败')
       }
         this.$message.success('创建商品成功')
         this.$router.push('/goods')
      });
    }
  },
  computed: {
    cartId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    }
  }
};
</script>
<style lang="less" scoped>
.el-steps {
  margin: 15px;
}
.el-step-title {
  font-size: 14px;
}
.el-checkbox {
  margin: 0;
}
.picSee {
  width: 95%;
}
.el-button {
  margin-top: 20px;
}
</style>